package com.utils;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class FileBase64Utils {

    /**
     * 将文件转成base64 字符串
     *
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code base64字符串
     * @param targetPath 文件地址
     * @throws Exception
     */
    public static void decodeBase64File(String base64Code, String targetPath) throws Exception {
        File file = new File(targetPath);
        if (!file.getParentFile().exists()) {
            file.mkdirs();
        }
        byte[] buffer = Base64.getDecoder().decode(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }


}